package com.cskaoyan.shopping.service.impl;

import com.cskaoyan.mall.commons.exception.ExceptionProcessorUtils;
import com.cskaoyan.mall.constant.ShoppingRetCode;
import com.cskaoyan.mall.dto.ClearCartItemRequest;
import com.cskaoyan.mall.dto.ClearCartItemResponse;
import com.cskaoyan.shopping.converter.CartItemConverter;
import com.cskaoyan.shopping.dal.entitys.Item;
import com.cskaoyan.shopping.dal.persistence.ItemMapper;
import com.cskaoyan.shopping.dto.*;
import com.cskaoyan.shopping.dto.CartProductDto;
import com.cskaoyan.shopping.service.ICartService;
import org.redisson.api.RMap;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import java.util.*;


/**
 * @auther cskaoyan
 * @date 2022/6/16:16:34
 */
@Service
public class ICartSeviceImpl implements ICartService {

    @Autowired
    ItemMapper itemMapper;

    @Autowired
    RedissonClient redissonClient;

    @Override
    public CartListByIdResponse getCartListById(CartListByIdRequest request) {
        try {
            CartListByIdResponse listByIdResponse = new CartListByIdResponse();
            List<CartProductDto> productDtos = new ArrayList<>();
            Long userId = request.getUserId();
            RMap<Long, CartProductDto> map = redissonClient.getMap(userId + "");
            Set<Long> longs = map.keySet();
            for (Long key : longs) {
                CartProductDto cartProductDto = map.get(key);
                productDtos.add(cartProductDto);
            }
            listByIdResponse.setCartProductDtos(productDtos);
            listByIdResponse.setCode(ShoppingRetCode.SUCCESS.getCode());
            listByIdResponse.setMsg(ShoppingRetCode.SUCCESS.getMessage());
            return listByIdResponse;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;

    }

    @Override
    public AddCartResponse addToCart(AddCartRequest request) {
        try {
            AddCartResponse cartResponse = new AddCartResponse();
            RMap<Object, Object> cart = redissonClient.getMap("" + request.getUserId());
            Item item = itemMapper.selectByPrimaryKey(request.getItemId());
            item.setNum(request.getNum());
            CartProductDto productDto = CartItemConverter.item2Dto(item);
            productDto.setChecked("false");
            productDto.setProductNum((long)request.getNum());
            CartProductDto cartProductDto = (CartProductDto) cart.get(request.getItemId());
            if (cartProductDto == null || cartProductDto.getProductNum() == null){
                cart.put(request.getItemId(), productDto);
            }else {
                cartProductDto.setProductNum(cartProductDto.getProductNum()+request.getNum());
                cart.put(request.getItemId(), cartProductDto);
            }
            cartResponse.setCode(ShoppingRetCode.SUCCESS.getCode());
            cartResponse.setMsg(ShoppingRetCode.SUCCESS.getMessage());
            return cartResponse;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public UpdateCartNumResponse updateCartNum(UpdateCartNumRequest request) {

        try {
            UpdateCartNumResponse response = new UpdateCartNumResponse();
            RMap<Object, Object> map = redissonClient.getMap("" + request.getUserId());
            CartProductDto cartProductDto = (CartProductDto) map.get(request.getItemId());
            cartProductDto.setChecked(request.getChecked());
            cartProductDto.setProductNum((long) request.getNum());
            map.put(request.getItemId(), cartProductDto);
            response.setCode(ShoppingRetCode.SUCCESS.getCode());
            response.setMsg(ShoppingRetCode.SUCCESS.getMessage());
            return response;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;

    }


    // @Autowired
    // RedissonClient redissonClient;
    @Override
    public CheckAllItemResponse checkAllCartItem(CheckAllItemRequest request) {
        CheckAllItemResponse checkAllItemResponse = new CheckAllItemResponse();

        try {
            request.requestCheck();
            // TODO:真正的逻辑，需要知道Redis中所传的对象具体是啥，然后将对象中checked改为request中提供的值
            String userId = String.valueOf(request.getUserId());
            RMap<Object, CartProductDto> map = redissonClient.getMap(userId);
            Collection<CartProductDto> values = map.values();
            for (CartProductDto value : values) {
                value.setChecked(request.getChecked());
                map.fastReplace(value.getProductId(), value);
            }
            //成功执行
            checkAllItemResponse.setCode(ShoppingRetCode.SUCCESS.getCode());
            checkAllItemResponse.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            ExceptionProcessorUtils.wrapperHandlerException(checkAllItemResponse, e);
        }
        return checkAllItemResponse;
    }


    @Override
    public DeleteCartItemResponse deleteCartItem(DeleteCartItemRequest request) {
        DeleteCartItemResponse deleteCartItemResponse = new DeleteCartItemResponse();
        try {
            request.requestCheck();
            Long userId = request.getUserId();
            Long itemId = request.getItemId();
            redissonClient.getMap(String.valueOf(userId)).remove(itemId);
            deleteCartItemResponse.setCode(ShoppingRetCode.SUCCESS.getCode());
            deleteCartItemResponse.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            ExceptionProcessorUtils.wrapperHandlerException(deleteCartItemResponse, e);
        }

        return deleteCartItemResponse;
    }

    @Override
    public DeleteCheckedItemResposne deleteCheckedItem(DeleteCheckedItemRequest request) {
        DeleteCheckedItemResposne deleteCheckedItemResposne = new DeleteCheckedItemResposne();
        try {
            request.requestCheck();
            Long userId = request.getUserId();
            Map<Long, CartProductDto> map = redissonClient.getMap(String.valueOf(userId));
            Iterator<Map.Entry<Long, CartProductDto>> it = map.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry<Long, CartProductDto> entry = it.next();
                if(entry.getValue().getChecked().equals("true")) {
                    map.remove(entry.getKey());
                }
            }
            deleteCheckedItemResposne.setCode(ShoppingRetCode.SUCCESS.getCode());
            deleteCheckedItemResposne.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            ExceptionProcessorUtils.wrapperHandlerException(deleteCheckedItemResposne, e);
        }
        return deleteCheckedItemResposne;
    }



    @Override
    public ClearCartItemResponse clearCartItemByUserID(ClearCartItemRequest request) {
        ClearCartItemResponse clearCartItemResponse = new ClearCartItemResponse();
        try {
            request.requestCheck();
            Long userId = request.getUserId();
            List<Long> productIds = request.getProductIds();
            Map<Long, CartProductDto> map = redissonClient.getMap(String.valueOf(userId));
            Iterator<Map.Entry<Long, CartProductDto>> it = map.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry<Long, CartProductDto> entry = it.next();

                for (Long productId : productIds) {
                    if(entry.getKey().equals(productId)) {
                        map.remove(entry.getKey());
                    }
                }

            }
            clearCartItemResponse.setCode(ShoppingRetCode.SUCCESS.getCode());
            clearCartItemResponse.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            ExceptionProcessorUtils.wrapperHandlerException(clearCartItemResponse, e);
        }
        return clearCartItemResponse;
    }
}
